package com.gao.security.verificationcode.validatecode.img;

import com.gao.security.verificationcode.base.BaseCode;
import com.gao.security.verificationcode.base.BaseCodeOperationManager;
import com.gao.security.verificationcode.exception.ValidateCodeRenderException;
import com.gao.security.verificationcode.validatecode.AbstractVerificationCodeHandler;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.BeanNameAware;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.validation.constraints.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 谷歌默认验证码组件
 *
 * @author gaoshuangwen
 */

public class GoogleKaptchaImgCodeVerificationCodeHandler extends AbstractVerificationCodeHandler  {

    private DefaultKaptcha kaptcha;

    public GoogleKaptchaImgCodeVerificationCodeHandler(DefaultKaptcha kaptcha, BaseCodeOperationManager codeStorageStrategy) {
        super(codeStorageStrategy);
        this.kaptcha=kaptcha;
    }

    @Override
    public String getCode() {
        return kaptcha.createText();
    }

    public Map<String, String> returnMap(BaseCode baseCode) {
        Map<String,String> map=Maps.newHashMap();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(kaptcha.createImage(baseCode.getCode()), "jpg", out);
        } catch (IOException e) {
            throw new ValidateCodeRenderException("ValidateCode render exception");
        }
        BASE64Encoder encoder = new BASE64Encoder();
        map.put("imgCode",encoder.encode(out.toByteArray()));
        map.put("key",baseCode.getUuid());
        return map;
    }

}